import configparser
import pickle
import os
import random

class SHandler_extern:
    def __init__(self):
        self.cfg = configparser.ConfigParser()

        cfg_path = os.path.expanduser("~/.config/remoteFileMgr.ini")
        if os.path.isfile(cfg_path):
            self.cfg.read(cfg_path)
        else:
            print("Config file not found, user input required for "
                  "first time configuration.")

            self.cfg['remote'] = {}
            genkey = ''
            for i in range(32):
                genkey += chr(random.randint(97, 122))
            self.cfg['remote']['cipher_key'] = genkey

            self.cfg['remote']['max_sessions'] = '4'
            self.cfg['telegram'] = {}
            self.cfg['telegram']['api_id'] = ''
            self.cfg['telegram']['api_hash'] = ''
            self.cfg['telegram']['channel_id'] = 'me'
            self.cfg['paths'] = {}
            self.cfg['paths']['data_path'] = os.path.expanduser("~")
            self.cfg['paths']['tmp_path'] = os.path.expanduser("~/.tmp")
            self.cfg['paths']['download_full_path'] = 'false'
            self.cfg['keybinds'] = {}
            self.cfg['keybinds']['upload'] = 'u'
            self.cfg['keybinds']['download'] = 'd'
            self.cfg['keybinds']['resume'] = 'r'
            self.cfg['keybinds']['cancel'] = 'c'
            self.cfg['telegram']['api_id'] = input("api_id: ")
            self.cfg['telegram']['api_hash'] = input("api_hash: ")

            with open(cfg_path, 'w') as f:
                self.cfg.write(f)

        # Change these paths without writing the change to a file
        self.cfg['paths']['data_path'] = os.path.join(
                                self.cfg['paths']['data_path'], "remoteFileMgr")
        self.cfg['paths']['tmp_path'] = os.path.join(
                                 self.cfg['paths']['tmp_path'], "remoteFileMgr")

        for i in [os.path.join(self.cfg['paths']['data_path'], "downloads"),
                  self.cfg['paths']['tmp_path']]:
            if not os.path.isdir(i):
                os.makedirs(i)

        # load database
        self.fileDatabase = {'file': [], 'index': {}}
        self._database_path = os.path.join(self.cfg['paths']['data_path'],
                                           "fileData")

        if os.path.isfile(self._database_path):
            with open(self._database_path, 'rb') as f:
                self.fileDatabase = pickle.load(f)

        # load resume Data
        self.resumeData = {}
        self._resume_path = os.path.join(self.cfg['paths']['data_path'],
                                         "resume_{}")

        for i in range(1, int(self.cfg['remote']['max_sessions']) + 1):
            fileData = {}
            if os.path.isfile(self._resume_path.format(i)):
                with open(self._resume_path.format(i), 'rb') as f:
                    fileData = pickle.load(f)

            self.resumeData[i] = fileData


    def updateDatabase(self):
        with open(self._database_path, 'wb') as f:
            pickle.dump(self.fileDatabase, f)


    def saveResumeData(self, fileData: dict, sFile: int):
        self.resumeData[sFile] = fileData
        with open(self._resume_path.format(sFile), 'wb') as f:
            pickle.dump(fileData, f)


    def delResumeData(self, sFile: int):
        self.resumeData[sFile] = {}
        os.remove(self._resume_path.format(sFile))
